/**
 * Filename: GAGameStateGetHandler.js
 * Author: Abid Hussain
 * Date Created: 07/06/2011
 */
exports.GAGameStateGetHandler = Core.Class.singleton({
	classname: 'GAGameStateGetHandler',
	
	initialize: function(){
		this._delegate = null;
		this._error = null;
		this._totalFiles = null;
		this._userkey = null;
		this._baseUrl = null;
		this._dbPath = null;
		this._game = null;
		this._filesCount = null;
		this._lastModifiedTime = null;
		this._storage = new Storage.KeyValue();
		this._getServerParams();
	},
	
	/*
	 * Public method called by the user for gameStateGet.
	 * This method gets the game state from the server and stores it in user database
	 * */
	restoreGameState: function(delegate){
		this._delegate = delegate;
		this._error = false;
		this._totalFiles = 0;
		this._filesCount = 0;
		this._getGameStateInfo();
	},
	
	getNeighbourGameState: function(delegate, userId) {
		this._delegate = delegate;
		this._error = false;
		this._totalFiles = 0;
		this._filesCount = 0;
		if(userId)
		{
			this._neighbourUserId = userId;
		}
		else
		{
			this._neighbourUserId = "0";
		}
		this._isNeighbourGameState = true;
		this._getNeighbourGameStateInfo();
	},
	
	_getServerParams: function(){
		var responseObject = GAGameLoader.getResponseObject();
		if(responseObject != null){
			this._baseUrl = GAConfigurations.getURL();//responseObject.getGameServer();
			this._userkey = GAConfigurations.getRecordID();
			this._game = GAConfigurations.getGameCode();
			this._dbPath = GAConfigurations.getGameStateDBPath();
		}
	},
	_getGameStateInfo: function(){
		//var InfoBaseUrl = this._baseUrl.replace('/gameState','/getGameStateInfo');
		var InfoBaseUrl = this._baseUrl+"get_game_db";
		var url = InfoBaseUrl+'?unique_id='+this._userkey;
		console.log("Zuluuu::: Basic Gamestate Get URL "+url);
		var fetcher = new GAWebFetcher(this,30,0);
		fetcher.invokeGetRequest(url);
	},
	
	_getNeighbourGameStateInfo: function(){
		var InfoBaseUrl = GAConfigurations.getURL()+"get_game_db";
		var url = InfoBaseUrl+'?unique_id='+this._neighbourUserId+'&XP=1';
		console.log("Zuluuu::: Basic Neighbour Gamestate Get URL "+url);
		var fetcher = new GAWebFetcher(this,30,0);
		fetcher.invokeGetRequest(url);
	},
	
	
	/*
	 * webFetchSuccess: this is called in response of _getGameStateInfo function call and is callback of webFetcher class.
	 * */
	webFetchSuccess: function(webFetcher, responseData){
		console.log("Zuluuu::: GameState Info Get Success");
		try{
			var serverResponse = eval("("+ responseData +")");
			this._responseObject = serverResponse;
			var status = serverResponse.status;
			console.log("zuluuu::: RESPONSE status"+status);
			if(status == true)
			{
				if(this._isNeighbourGameState)
				{
					this._neighbourGameStateGet();
				}
				else
				{
					this._gameStateGet();
				}
			} 
			else if (status == false)
			{
				if(this._isNeighbourGameState)
				{
					this.webFetchFailure(webFetcher, null);
					return;
				}
				console.log("Zuluuu::: Gamestate not found .. Moving start");
				//Move DB from DB PAth to Actual Path
				var dbFileNames = GAConfigurations.getDbFileNames();
				for(var i=0 ; i<dbFileNames.length ; i++)
				{
					dbFileNames[i] = dbFileNames[i]+".json";
				}
				var sourcePath = GAConfigurations.getGameStateDBPath()+"/";
				var destinationPath = sourcePath+GAConfigurations.getRecordID()+"/";
				
				this.moveDbFiles(sourcePath, destinationPath, dbFileNames);
				
			}
			else 
			{
				this._delegate.gameStateGetFailure();
			}
			/*var data = serverResponse.data;
			var serverLMTime = data.gamestatelastupdatetime;
			if(serverLMTime != null){
				serverLMTime  = this._dateFromUTC(serverLMTime, "-");
				this._serverLastModifiedTime = Date.parse(serverLMTime);
			}
			else{
				this._serverLastModifiedTime = -1;
                //this._serverLastModifiedTime = serverResponse.currentservertime;
			}
			this._saveLastModifiedTime(this._serverLastModifiedTime);
			
			this._gameStateGet();
			*/
		}
		catch(exception){
			this._delegate.gameStateGetFailure(exception);
		}
		finally{
			if(webFetcher != null){
				webFetcher.destroy();
				webFetcher = null;
			}
		}
	},
	/*
	 * webFetchFailure: this is called in response of _getGameStateInfo function call and is call back of webFetcher class.
	 * */
	webFetchFailure: function(webFetcher, error){
		console.log("Zuluuu::: GameState Info Get Failure ");
		if(this._delegate != null){
			this._delegate.gameStateGetFailure(error);
		}
		if(webFetcher != null){
			webFetcher.destroy();
			webFetcher = null;
		}
	},
	
	moveDbFiles: function(source, destination, filesArray)
	{
		console.log("Zuluuu::: Source "+source+" Destination "+destination+" Files Array "+filesArray);
		GACopyManager.copy(filesArray, source, destination, true, this.moveDbFilesProgressCallback.bind(this), this.moveDbFilesSuccessCallback.bind(this), this.moveDbFilesFailureCallback.bind(this))
	},
	
	moveDbFilesSuccessCallback: function()
	{
		console.log("Zuluuu::: Move DB Files done");
		this._delegate.gameStateGetSuccess();
	},
	
	moveDbFilesFailureCallback: function()
	{
		console.log("Zuluuu::: Move DB Files Failed");
		this._delegate.gameStateGetFailure();
	},
	
	moveDbFilesProgressCallback: function()
	{
		
	},
	
	_gameStateGet: function(){
		//var url = this._getUrl();
		var url = this._responseObject.db_path+"?unique_id="+this._userkey;
		console.log("Zuluuu::: Final Download URL "+url);
		console.log("Zuluuu::: Destination "+this._dbPath+'/gameState.zip');
		var fileDownloader = new GAFileDownloader(this._dbPath+'/gameState.zip' ,'GET' ,url ,null ,this);
		fileDownloader.startDownloading();
	},
	
	//getNeighborState: function(type, userkey, successCb, failureCb){
	_neighbourGameStateGet: function(){
		
		var url = this._responseObject.db_path+"?unique_id="+this._neighbourUserId;
		console.log("Zuluuu::: Final Download URL "+url);
		console.log("Zuluuu::: Destination "+this._dbPath+'/neighbour/neighbuor.zip');
		var fileDownloader = new GAFileDownloader(this._dbPath+'/neighbour/neighbour.zip' ,'GET' ,url ,null ,this);
		fileDownloader.startDownloading();
		
		
		/*this._requestType = type;
		this._neighborKey = userkey;
		this._successCb = successCb;
		this._failureCb = failureCb;
		var url = this._constructURL(this._requestType, this._neighborKey);
		var fileDownloader = new GAFileDownloader(this._dbPath+'/neighbor.zip' ,'GET' ,url ,null ,this, "neighborGameState");
		fileDownloader.startDownloading();*/
	},
	
	_constructURL : function(type, usekey){
		/*var url = [];
		url.push(this._baseUrl);
		url.push("?type="+type);
		url.push("&userkey=");
		url.push(usekey);
		url.push("&udid=");
		url.push(GAConfigurations.getUdid());
		url.push('&osType=android');          //OSType is hard coded temporarily...
		//url.push(GAConfigurations.getPlatformOS());
		url.push('&game=');
		url.push(GAConfigurations.getGameCode());
		url.push('&json=1');
		url.push('&encoding=base64zip');
		url = encodeURI(url.join(""));
		*/
		var url = this._responseObject.db_path+"?unique_id=0&XP=1";
		return url;
	},
	
	/*
	 * This function returns the URL for the gameStateGet
	 * */
	_getUrl: function(){
		var url ='';
		var gStateBaseUrl = this._baseUrl.replace('/gameState','/dbfile');
		url = gStateBaseUrl+'?'+'type=userkey&udid='+ this._userkey +'&game='+ this._game +'&encoding=base64';
		return url;
	},
	

	onDownloadSuccess: function(downloader,fileSignature){
		console.log("Zuluuu:: Download Gamestate Success");
		/*var destination = GAConfigurations.getGameStateDBPath() + '/' + this._userkey + '/';
		Storage.FileSystem.decompressFile(this._dbPath+'/gameState.zip',destination,true,this._zipExtractionCb.bind(this));
		* */
		if(!this._isNeighbourGameState){
			var destination = this._dbPath + '/' + this._userkey + '/';
			Storage.FileSystem.decompressFile(this._dbPath+'/gameState.zip',destination,true,this._zipExtractionCb.bind(this));
		}
		else {
			var destination = this._dbPath + '/neighbour/'+this._neighbourUserId+'/' ;
			Storage.FileSystem.decompressFile(this._dbPath+'/neighbour/neighbour.zip', destination, true, this._zipExtractionCb.bind(this));
		}
		if(downloader != null){
			downloader.destroy();
			downloader = null;
		}
		
	},
	onDownloadFailure: function(downloader,error){
		console.log("Zuluuu:: Download Gamestate Failure");
		this._delegate.gameStateGetFailure('onDownloadFailure = '+error);
	},
	
	_zipExtractionCb: function(error,files){
		if(!error){
			if(this._isNeighbourGameState)
			{
				console.log("Zuluuu::: Neighour Get Pass");
				Storage.FileSystem.deleteFile(this._dbPath+'/neighbour/neighbour.zip');
				//var destination = this._dbPath + '/' + this._userkey + '/';
				var destination = this._dbPath + '/neighbour/'+this._neighbourUserId+'/' ;
				this._delegate.gameStateGetSuccess(destination);
			} 
			else
			{
				Storage.FileSystem.deleteFile(this._dbPath+'/gameState.zip');
				this._delegate.gameStateGetSuccess();
			}
		}
		else{
			this._delegate.gameStateGetFailure('Error while extracting gameState file.');
		}
	},

	_dateFromUTC: function( dateAsString, ymdDelimiter ){
		 var pattern = new RegExp( "(\\d{4})" + ymdDelimiter + "(\\d{2})" + ymdDelimiter + "(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})" );
		 var parts = dateAsString.match( pattern );
		 return new Date(Date.UTC(parseInt( parts[1] ), parseInt( parts[2], 10 ) - 1, parseInt( parts[3], 10 ), parseInt( parts[4], 10 ), parseInt( parts[5], 10 ), parseInt( parts[6], 10 ),0));
	},
	_saveLastModifiedTime: function(value){
		this._storage.setItem(kGAGameState.kLastModifiedTime,value);
	},
	
	destroy: function(){
		this._delegate = null;
		this._error = null;
		this._filesCount = null;
		this._totalFiles = null;
		this._lastModifiedTime = null;
		this._storage = null;
		this._userkey = null;
		this._baseUrl = null;
		this._dbPath = null;
		this._game = null;
	}
});